﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;

namespace Simple.Admin.System;

public class MenuManager : DomainService
{
    private readonly IMenuEntityRepository _menuRepository;
    public MenuManager(IMenuEntityRepository menuEntityRepository)
    {
        _menuRepository = menuEntityRepository;
    }

    /// <summary>
    /// 创建菜单
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <exception cref="BusinessException"></exception>
    public async Task CreateAsync(MenuEntity input)
    {
        if (await _menuRepository.AnyAsync(x => x.Name == input.Name))
        {
            throw new BusinessException($"菜单名字{input.Name}已存在");
        }
        if (input.ParentId.HasValue && !await _menuRepository.AnyAsync(x => x.Path == input.Path))
        {
            throw new BusinessException($"菜单路径{input.Path}已存在");
        }

        // Create the new menu entity
        await _menuRepository.InsertAsync(input);
    }

    public async Task DeleteAsync(Guid id)
    {
        var menu = await _menuRepository.GetAsync(x => x.Id == id);
        if (menu == null)
        {
            throw new BusinessException($"菜单不存在，Id：{id}");
        }
        var children = await GetChildrenAsync(id);
        if (children.Count > 0)
        {
            throw new BusinessException($"菜单下有子菜单，无法删除，Id：{id}");
        }
        await _menuRepository.DeleteAsync(menu);
    }

    public async Task<List<MenuEntity>> GetChildrenAsync(Guid id)
    {
        return await _menuRepository.GetChildrenAsync(id);
    }
}
